//
//  MyLayout.m
//  testZhengShu
//
//  Created by Garlic on 2020/3/27.
//  Copyright © 2020 garlic. All rights reserved.
//

#import "MyLayout.h"
#import "MyCustomAttributes.h"

#define INSET_TOP 10
#define INSET_LEFT 10
#define INSET_BOTTOM 10
#define INSET_RIGHT 10

@interface MyLayout()
 
@property (nonatomic) NSDictionary *layoutInformation;
@property (nonatomic) NSInteger maxNumRows;
@property (nonatomic) UIEdgeInsets insets;

 
@end

@implementation MyLayout

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.insets = UIEdgeInsetsMake(INSET_TOP, INSET_LEFT, INSET_BOTTOM, INSET_RIGHT);
    }
    return self;
}

- (MyCustomAttributes *)attributesWithChildrenAtIndexPath:(NSIndexPath *)indexPath{
    MyCustomAttributes *atr = [MyCustomAttributes layoutAttributesForCellWithIndexPath:indexPath];

    //根据数据信息需要把child的indexPath存入到atr.children中
    //这里强行假设测试
    if (indexPath.section == 1 && indexPath.row == 1) {
        atr.children = @[[NSIndexPath indexPathForItem:0 inSection:2],
                         [NSIndexPath indexPathForItem:1 inSection:2],
                         ];
    }
    if (indexPath.section == 1 && indexPath.row == 2) {
        atr.children = @[[NSIndexPath indexPathForItem:2 inSection:2],
                         [NSIndexPath indexPathForItem:3 inSection:2],
                         ];
    }
//    NSLog(@"aaaaaa===%@------%@",atr.children,atr);
    return atr;
}

- (CGRect)frameForCellAtIndexPath:(NSIndexPath *)indexPath withHeight:(NSInteger)height{
    //NSLog(@"%@====%zd",indexPath,height);
    CGFloat x = indexPath.section * 120;
    CGFloat y = height * 50 ;
    return CGRectMake(x, y, 100, 40);
}

- (void)adjustFramesOfChildrenAndConnectorsForClassAtIndexPath:(NSIndexPath *)indexPath attr:(MyCustomAttributes *)attr cellInformation:(NSDictionary *)cellInformation totalHeight:(NSInteger)totalHeight{
    //根据indexPath 查找 有几个child 并且调整child的位置
    //以递归方式调整该单元格的所有子代和孙辈的框架，以此类推以匹配该单元格的框架。（apple）
    //1 根据indexPath 查找 对应的MyCustomAttributes
   
    for (int i = 0; i<attr.children.count; i++) {
        NSIndexPath *childIndexPath = attr.children[i];
        MyCustomAttributes *childAtr = [cellInformation objectForKey:childIndexPath];
        CGRect childFrame = childAtr.frame;
        CGFloat ajustY = attr.frame.origin.y + i * 50;
        childAtr.frame = CGRectMake(childFrame.origin.x, ajustY, 100, 40);
    }

}

- (void)prepareLayout{
    [super prepareLayout];
    
    NSMutableDictionary *layoutInformation = [NSMutableDictionary dictionary];
    NSMutableDictionary *cellInformation = [NSMutableDictionary dictionary];
    NSIndexPath *indexPath;
    NSInteger numSections = [self.collectionView numberOfSections];
    
       for(NSInteger section = 0; section < numSections; section++){
           NSInteger numItems = [self.collectionView numberOfItemsInSection:section];
           for(NSInteger item = 0; item < numItems; item++){
               
               indexPath = [NSIndexPath indexPathForItem:item inSection:section];
               
               MyCustomAttributes *attributes = [self attributesWithChildrenAtIndexPath:indexPath];
               
               [cellInformation setObject:attributes forKey:indexPath];
           }
       }
    //continuation of prepareLayout implementation
    for(NSInteger section = numSections - 1; section >= 0; section--){
        NSInteger numItems = [self.collectionView numberOfItemsInSection:section];
        //需要向下几行
        NSInteger totalHeight = 0;
        for(NSInteger item = 0; item < numItems; item++){
            indexPath = [NSIndexPath indexPathForItem:item inSection:section];
            MyCustomAttributes *attributes = [cellInformation objectForKey:indexPath]; // 1
            attributes.frame = [self frameForCellAtIndexPath:indexPath
                                withHeight:totalHeight];
            //调整child的位置
            [self adjustFramesOfChildrenAndConnectorsForClassAtIndexPath:indexPath attr:attributes cellInformation:cellInformation totalHeight:totalHeight]; // 2

            cellInformation[indexPath] = attributes;
            totalHeight += [self.customDataSource
                            numRowsForClassAndChildrenAtIndexPath:indexPath]; // 3
            
//            NSLog(@"indexPath=%@==totalHeight===%zd======%@",indexPath,totalHeight,self.layoutInformation);
//            NSLog(@"11111==%@",attributes);
        }
        if(section == 0){
            self.maxNumRows = totalHeight; // 4
        }
    }
    [layoutInformation setObject:cellInformation forKey:@"MyCellKind"]; // 5
    self.layoutInformation = layoutInformation;
    
    NSLog(@"=========*******============");
}

- (CGSize)collectionViewContentSize {
    CGFloat width = self.collectionView.numberOfSections * (100 + self.insets.left + self.insets.right);
    CGFloat height = self.maxNumRows * (40 + _insets.top + _insets.bottom);
    return CGSizeMake(width, height);
}


- (NSArray*)layoutAttributesForElementsInRect:(CGRect)rect {
    NSMutableArray *myAttributes = [NSMutableArray arrayWithCapacity:self.layoutInformation.count];
    for(NSString *key in self.layoutInformation){
        NSDictionary *attributesDict = [self.layoutInformation objectForKey:key];
        for(NSIndexPath *key in attributesDict){
            UICollectionViewLayoutAttributes *attributes =
            [attributesDict objectForKey:key];
            if(CGRectIntersectsRect(rect, attributes.frame)){
                [myAttributes addObject:attributes];
            }
        }
    }
    return myAttributes;
}

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
    return self.layoutInformation[@"MyCellKind"][indexPath];
}
@end
